import { Component, Input, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Message } from 'primeng/components/common/api';
import { MessageService } from 'primeng/api';
import { ToastModule } from 'primeng/toast';
import { DialogModule } from 'primeng/dialog';
import { Utils } from '../utils/utils';

/**
 * 本组件用于自动显示消息和等待ajax请求的遮罩。
 * @example
 * 在app.moudle.ts中
 * import { MessageBoxModule } from 'iisp-ng';
 * import {MessageService} from "primeng/api";
 *  
 *  NgModule({
 *  imports: [MessageBoxModule,...],
 *  providers: [MessageService,...]
 * 
 * 在html末尾加上如下行
 * <i-mbox [isRunning]="isRunning()"></i-mbox>
 */
@Component( {
    selector: 'i-mbox',
    template: `<p-toast key='_iispMbox'></p-toast>
	    <p-dialog [modal]="true" [header]="header" [draggable]="false" [closable]="false" [visible]="isRunning" [width]="150" 
            [height]="188" [minWidth]="148" [minHeight]="128" >
        <div style="margin-left: 60px" class="loading"></div>
	</p-dialog>`
} )
export class MessageBoxComponent {
    @Input() isRunning: boolean;
    constructor( public messageService: MessageService ) { }
    header = Utils.resolveLocalizedMessage( 'loading.data' );
    static lifeTimeMap = {
        "success": 5, "info": 20, "warn": 20, "error": 60
    }
    static G_MBOX_ID = '_iispMbox';
    showMessage( style: string, msg: string, mboxId = MessageBoxComponent.G_MBOX_ID): void {
        let title = Utils.resolveLocalizedMessage( "msg.type." + style );
        this.messageService.add( {key: mboxId, life: MessageBoxComponent.lifeTimeMap[style] * 1000, severity: style, summary: title, detail: msg } );
    }
    showMessages( style: string, messages: string[], mboxId = MessageBoxComponent.G_MBOX_ID ): void {
        let msgs = [];
        for ( let msg of messages ) {
            let title = Utils.resolveLocalizedMessage( "msg.type." + style );
            msgs.push( {key: mboxId, life: MessageBoxComponent.lifeTimeMap[style] * 1000, severity: style, summary: title, detail: msg } );
        }
        this.messageService.addAll( msgs );
    }
    clear() {
        this.messageService.clear();
    }
    getOffset(): any {
        //让消息框在屏幕可见区中间
        let clientWidth = document.documentElement.clientWidth;
        let clientHeight = document.documentElement.clientHeight;
        let top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
        let left = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
        let x = ( clientWidth - 100 ) / 2 + left;
        let y = ( clientHeight - 30 ) / 2 + top;
        //console.debug("x=" + x + "y=" + y + "document.body.scrollTop=" + top);
        return { left: x, top: y };
    }
}

@NgModule( {
    imports: [CommonModule, ToastModule, DialogModule],
    exports: [MessageBoxComponent],
    declarations: [MessageBoxComponent]
} )
export class MessageBoxModule { }